package com.hpin.fansea.alipay;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.alipay.android.app.sdk.AliPay;
import com.hpin.fansea.my.MyOrderActivity;
import com.hpin.fansea.my.PayRecordActivity;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.LogUtil;

import java.net.URLEncoder;

public class AlipayEx {

    public static final String TAG = "AlipayEx";
    private static final int RQF_PAY = 1;
    private static final int RQF_LOGIN = 2;

    private static String notify_url = "http://notify.java.jpxx.org/index.jsp";
    private static String return_url = "http://m.alipay.com";

    private static Activity context;

	/*
     * public AlipayEx(Context context) { super(); this.context = context; }
	 */

    /**
     * 启动支付宝支付
     *
     * @param act
     * @param tn        订单号
     * @param subject   商品主题
     * @param body      商品描述
     * @param total_fee 金额，例：0.01表示1分钱
     */
    public static void doStartAlipay(final Activity act, String tn,
                                     String subject, String body, String total_fee) {
        try {
            context = act;

            String info = getOrderInfo(tn, subject, body, total_fee);
            String sign = Rsa.sign(info, Keys.PRIVATE);
            sign = URLEncoder.encode(sign);
            info += "&sign=\"" + sign + "\"&" + getSignType();
            final String orderInfo = info;

            new Thread() {
                public void run() {
                    AliPay alipay = new AliPay(context, mHandler);

                    // 设置为沙箱模式，不设置默认为线上环境
                    // alipay.setSandBox(true);

                    String result = alipay.pay(orderInfo);
                    Log.i(TAG, "result = " + result);
                    Message msg = new Message();
                    msg.what = RQF_PAY;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            }.start();

        } catch (Exception ex) {
            ex.printStackTrace();
            Toast.makeText(context, "调用远程服务失败！", Toast.LENGTH_SHORT).show();
        }
    }

    private static String currentPayType = "";//支付类型

    /**
     * @param type        支付类型
     * @param act         上下文对象
     * @param tn          商户网站唯一订单号
     * @param subject     商品名称
     * @param body        商品详情
     * @param total_fee   商品金额
     * @param _notify_url 服务器异步通知页面路径
     * @param _return_url
     */
    public static void doStartAlipay(String type, final Activity act, String tn,
                                     String subject, String body, String total_fee, String _notify_url,
                                     String _return_url) {
        try {
            currentPayType = type;

            context = act;
            if (body == null || body.length() == 0)
                body = subject;
            if (_notify_url != null && _notify_url.length() > 0)
                notify_url = _notify_url;
            if (_return_url != null && _return_url.length() > 0)
                return_url = _return_url;

            String info = getOrderInfo(tn, subject, body, total_fee);
            String sign = Rsa.sign(info, Keys.PRIVATE);
            sign = URLEncoder.encode(sign);
            info += "&sign=\"" + sign + "\"&" + getSignType();
            final String orderInfo = info;

            new Thread() {
                public void run() {
                    AliPay alipay = new AliPay(context, mHandler);

                    // 设置为沙箱模式，不设置默认为线上环境
                    // alipay.setSandBox(true);

                    String result = alipay.pay(orderInfo);
                    Log.i(TAG, "result = " + result);
                    Message msg = new Message();
                    msg.what = RQF_PAY;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            }.start();

        } catch (Exception ex) {
            ex.printStackTrace();
            Toast.makeText(context, "调用远程服务失败！", Toast.LENGTH_SHORT).show();
        }
    }


    private static Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            Result result = new Result((String) msg.obj);
//
//            LogUtil.e("tag", "支付code=====" + msg.what);
            LogUtil.e("tag", "支付消息=====Result:" + result.getResult() + ",,ResultStatus:" + result.getResultStatus() + ",,result.getResultCode():" + result.getResultCode());

//            result.getResultStatus();

            if ("9000".equals(result.getResultCode())) {
                //支付成功

                if (Constant.PAY_PROPERTY.equals(currentPayType)) {//物业费支付成功

                    Intent mIntent = new Intent(context, PayRecordActivity.class);
                    context.startActivity(mIntent);

                } else if (Constant.PAY_GOODS.equals(currentPayType)) {//商品支付成功
                    Intent nIntent = new Intent(context, MyOrderActivity.class);
                    context.startActivity(nIntent);
                }

            } else {
                Toast.makeText(context, result.getResultStatus(), Toast.LENGTH_SHORT);
            }
        }

    };


    private static String getOrderInfo(String tn, String subject, String body,
                                       String total_fee) {
        StringBuilder sb = new StringBuilder();
        sb.append("partner=\"");
        sb.append(Keys.DEFAULT_PARTNER);
        sb.append("\"&out_trade_no=\"");
        sb.append(tn);
        sb.append("\"&subject=\"");
        sb.append(subject);
        sb.append("\"&body=\"");
        sb.append(body);
        sb.append("\"&total_fee=\"");
        sb.append(total_fee);
        sb.append("\"&notify_url=\"");

        // 网址需要做URL编码
        sb.append(URLEncoder.encode(notify_url));
        sb.append("\"&service=\"mobile.securitypay.pay");
        sb.append("\"&_input_charset=\"UTF-8");
        sb.append("\"&return_url=\"");
        sb.append(URLEncoder.encode(return_url));
        sb.append("\"&payment_type=\"1");
        sb.append("\"&seller_id=\"");
        sb.append(Keys.DEFAULT_SELLER);

        // 如果show_url值为空，可不传
        // sb.append("\"&show_url=\"");
        sb.append("\"&it_b_pay=\"1m");
        sb.append("\"");

        return new String(sb);
    }

    private static String getSignType() {
        return "sign_type=\"RSA\"";
    }

//
//    private static String getOutTradeNo() {
//        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
//        Date date = new Date();
//        String key = format.format(date);
//
//        java.util.Random r = new java.util.Random();
//        key += r.nextInt();
//        key = key.substring(0, 15);
//        Log.d(TAG, "outTradeNo: " + key);
//        return key;
//    }

//    public static void test(Activity act) {
//        String tn = getOutTradeNo();
//        String subject = "虚拟游戏币";
//        String body = "虚拟游戏币";
//        String total_fee = "0.01";
//        doStartAlipay(act, tn, subject, body, total_fee);
//    }


//    private static String getResultMessage(String errorCode) {
//        String message = "";
//        if (errorCode.equals("9000")) {
//            message = "支付成功";
//        } else if (errorCode.equals("4000")) {
//            message = "系统异常";
//        } else if (errorCode.equals("4001")) {
//            message = "订单参数错误";
//        } else if (errorCode.equals("6001")) {
//            message = "用户取消支付";
//        } else if (errorCode.equals("6002")) {
//            message = "网络连接异常";
//        }
//        return message;
//    }
}
